package com.sise.wangzhan.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.sise.wangzhan.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @Classname PersonService
 * @Description TODO
 * @Date 2020/5/6 20:31
 * @Created by wangzhan
 */
@Component
public class PersonService {
    @Autowired
    private RestTemplate restTemplate;

    /*
    *   @HystrixCommand注解修饰方法getPerson, 并且配置了回退方法
    * */
    @HystrixCommand(fallbackMethod = "getPersonFallback")
    public Person getPerson(Integer id){
        //使用 RestTemplate  调用Eureka 服务
        Person p = restTemplate.getForObject(
            "http://eureka-feign-hystrix-provider/person/{personid}",Person.class,id
        );

        System.out.println(p);
        return p;
    }

    /*
    *   回调方法，返回一个默认的Person
    * */
    public Person getPersonFallback(Integer id){
        Person person = new Person(0,"回调",-1);
        person.setMessage("request  error");

        return  person;
    }


    /*
    *   测试配置， 设置命令执行的时间为1000毫秒， 设置命令执行的线程池大小为1
    *
    * */

    @HystrixCommand(
            fallbackMethod = "testConfigFallback",groupKey = "MyGroup",
            commandKey = "MyCommandKey", threadPoolKey = "MyCommandPool",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")
            },
            threadPoolProperties = {
                @HystrixProperty(name = "coreSize",value = "1")
            })
    public String testConfig() throws InterruptedException {
       Thread.sleep(1500);

       return "ok";
    }

    public String testConfigFallback(){
        return "Timeout-----error";
    }


    /*
    *   如果方法跳出MyException,
    * */
    @HystrixCommand(fallbackMethod = "testExceptionFallBack")
    public String testException() throws MyException {
        throw new MyException();
    }

    public String testExceptionFallBack(){
        return "Exception----error";
    }



}
